import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/application.dart';
import 'package:flutter_yn_goods/config/app_config.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_theme.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/utils/shared/shared_export.dart';
import 'package:get/get.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Application().initialize();

  // PackageInfo info = await PackageInfo.fromPlatform();
  await AppConfig.setup();
  runApp(MyApp(title: AppConfig.appName));
}

class MyApp extends StatelessWidget {
  final String title;

  const MyApp({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      builder: (context, child) {
        return GetMaterialApp(
          title: title,
          debugShowCheckedModeBanner: false,
          transitionDuration: const Duration(milliseconds: 210),
          theme: AppTheme.setTheme(),
          initialRoute: Application.initialRoute(),
          getPages: AppRoutes.pages,
          translations: AppTranslations(),
          // 多语言翻译表
          locale: SharedStorage().initialLocale() ?? Get.deviceLocale,
          // 自动使用系统语言
          fallbackLocale: const Locale('en', 'US'),
          // 如果系统语言不支持，默认使用英文
          supportedLocales: const [
            Locale('en', 'US'),
            Locale('zh', 'CN'),
            Locale('vi', 'VN'),
            Locale('ar', 'SA'), // 添加阿拉伯语
          ],
          // themeMode: ThemeMode.light,
          localizationsDelegates: GlobalMaterialLocalizations.delegates,
          builder: (context, widget) {
            return MediaQuery(
              data: MediaQuery.of(context)
                  .copyWith(textScaler: const TextScaler.linear(1.0)),
              child: FlutterEasyLoading(
                child: TapHideKeyboard(child: widget!),
              ),
            );
          },
        );
      },
    );
  }
}

class TapHideKeyboard extends StatelessWidget {
  final Widget child;

  const TapHideKeyboard({super.key, required this.child});

  static void closeKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        closeKeyboard(context);
      },
      child: child,
    );
  }
}
